package quik.member;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import comm.util.CommUtil;
import comm.util.QuikFileRenamePolicy;
import comm.util.QuikHashMap;
import comm.util.RequestManager;
import comm.util.SqlMapLoader;

public class MemberProc {
	public MemberProc() {}
	
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	public void registerMember(HashMap hm){
		try {
			String savingPw = CommUtil.md5(hm.get("MEMBER_PASSWORD").toString());
			hm.remove("MEMBER_PASSWORD");
			hm.put("MEMBER_PASSWORD", savingPw);
			hm.put("GROUP_SEQ",1);
			sqlMapper.insert("member.registerMember",hm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public boolean tryLogin(HttpServletRequest request) throws NumberFormatException, UnsupportedEncodingException{
		boolean result = false;
		try {
			QuikHashMap hm = new QuikHashMap();
			hm = RequestManager.getRequest(request);
			String inputPw = hm.get("MEMBER_PASSWORD").toString();
			hm.remove("MEMBER_PASSWORD");
			hm.put("MEMBER_PASSWORD", CommUtil.md5(inputPw));
			hm = (QuikHashMap) sqlMapper.queryForObject("member.tryLogin",hm);
			if(Integer.parseInt(hm.get("LOGINCONFIRM").toString())==1){
				request.getSession().setAttribute("SESSION_MEMBER_SEQ", hm.get("MEMBER_SEQ"));
				request.getSession().setAttribute("SESSION_MEMBER_EMAIL", hm.get("MEMBER_EMAIL"));
				request.getSession().setAttribute("SESSION_MEMBER_NICKNAME", hm.get("MEMBER_NICK"));
				if(hm.get("GROUP_SEQ")!=null)
					request.getSession().setAttribute("SESSION_MEMBER_GROUPSEQ", hm.get("GROUP_SEQ"));
				if(hm.get("GROUP_NAME")!=null)
					request.getSession().setAttribute("SESSION_MEMBER_GROUPNAME", hm.get("GROUP_NAME"));
				if(hm.get("IS_ADMIN")!=null && Integer.parseInt(hm.get("IS_ADMIN").toString())==1){
					request.getSession().setAttribute("SESSION_ADMIN", hm.get("MEMBER_SEQ"));
				}
			result = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	public String findPw(HttpServletRequest request){
		String result = null;
		
		try {
			result = String.valueOf(sqlMapper.queryForObject("member.findPw",RequestManager.getRequest(request).get("MEMBER_EMAIL").toString()));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	public String changePw(HttpServletRequest request) throws UnsupportedEncodingException{
		String result = "";
		QuikHashMap hm = RequestManager.getRequest(request);
		hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
		if(hm.get("MEMBER_PASSWORD").toString().equals(hm.get("MEMBER_PASSWORDC").toString())){
			try {
				String savingPw = CommUtil.md5(hm.get("MEMBER_PASSWORD").toString());
				hm.remove("MEMBER_PASSWORD");
				hm.put("MEMBER_PASSWORD", savingPw);
				sqlMapper.update("member.changePw",hm);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			result = "SUCCESS";
		}else{
			result = "FAIL";
		}
		return result;
	}
	public String changeNick(HttpServletRequest request) throws UnsupportedEncodingException{
		String result = "";
		QuikHashMap hm = RequestManager.getRequest(request);
		hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
		if(hm.get("MEMBER_NICK").toString().trim().length()>0 && !isDuplicatedNick(hm.get("MEMBER_NICK").toString())){
			try {
				sqlMapper.update("member.changeNick",hm);
				result = "SUCCESS";
			} catch (SQLException e) {
				result = "FAIL";
				e.printStackTrace();
			}
		}else{
			result = "FAIL";
		}
		return result;
	}
	
	
	public String imgUpload(HttpServletRequest request,String savePath){
		String result="";
		HashMap hm = new HashMap();
		File f = new File(savePath);
		f.mkdir();
		System.out.println(savePath);
		int sizeLimit = 5 * 1024 * 1024 ; // 5메가까지 제한 넘어서면 예외발생
		try{
			MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit,"UTF-8", new QuikFileRenamePolicy());
		 	Enumeration formNames=multi.getFileNames();  // 폼의 이름 반환
			String formName=(String)formNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
			String fileName=multi.getFilesystemName(formName); // 파일의 이름 얻기

		    if(fileName == null) { // 파일이 업로드 되지 않았을때
		    	result = "FAIL";
		    } else { // 파일이 업로드 되었을때
	    		System.out.println("업로드 성공 :"+fileName);
		        fileName=new String(fileName);
		        hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
		        hm.put("MEMBER_IMG", fileName);
		        sqlMapper.update("member.imgUpload",hm);
		        result = "SUCCESS";
		    } // end if
		} catch(Exception e) {
		    System.out.print("예외 상황 발생..! "+e.getMessage());
		    result = "FAIL";
		}
		return result;
	}
	
	
	public String getCurImg(HttpServletRequest request){
		String result = "";
		try {
			String file = (String) sqlMapper.queryForObject("member.getCurImg",request.getSession().getAttribute("SESSION_MEMBER_SEQ").toString());
			result = "./data/userImage/"+request.getSession().getAttribute("SESSION_MEMBER_SEQ")+"/"+file;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	private boolean isDuplicatedEmail(String str){
		boolean result = true;
		
		try {
			if(Integer.parseInt(sqlMapper.queryForObject("member.checkDuplicateEmail",str).toString()) == 0){
				result = false;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
		
	}
	private boolean isDuplicatedNick(String str){
		boolean result = true;
		
		try {
			if(Integer.parseInt(sqlMapper.queryForObject("member.checkDuplicateNick",str).toString()) == 0){
				result = false;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
		
	}
	
	public String checkValidMemberRegInfo(HttpServletRequest request) throws UnsupportedEncodingException{
		QuikHashMap hm = RequestManager.getRequest(request);
		
		try {
			String temp = sqlMapper.queryForObject("member.checkConnection").toString();
		} catch (SQLException e) {
			return "데이터베이스가 응답하지 않습니다.";
		}
		if(!(hm.containsKey("MEMBER_EMAIL") &&
				hm.containsKey("MEMBER_PASSWORD") &&
				hm.containsKey("MEMBER_PASSWORDC") &&
				hm.containsKey("MEMBER_NICKNAME"))){
			return "ERROR_INPUT_VALUES";
		}
		if(hm.get("MEMBER_EMAIL").toString().length()<1){
			return "ERROR_LENGTH_EMAIL";
		}
		if(!hm.get("MEMBER_PASSWORD").toString().equals(hm.get("MEMBER_PASSWORDC").toString())){
			return "ERROR_EQUAL_PASSWORD";
		}
		if(hm.get("MEMBER_PASSWORD").toString().length()<1){
			return "ERROR_LENGTH_PASSWORD";
		}
		if(hm.get("MEMBER_NICKNAME").toString().length()<1){
			return "ERROR_LENGTH_NICKNAME";
		}
		if(!CommUtil.isValidEmail(hm.get("MEMBER_EMAIL").toString())){
			return "ERROR_EMAIL_VALID";
		}
		if(isDuplicatedEmail(hm.get("MEMBER_EMAIL").toString())){
			return "ERROR_EMAIL_DUPLICATED";
		}
		if(isDuplicatedNick(hm.get("MEMBER_NICKNAME").toString())){
			return "ERROR_NICKNAME_DUPLICATED";
		}
		return "SUCCESS";
	}
	
	public ArrayList getUserArticle(String str,String pageSize,String curPage) {
		ArrayList lt = null;	
		HashMap hm = new HashMap();
		String _pageSize = "5";
		String _curPage="1";
		
		if(pageSize!=null)
			_pageSize = pageSize;
		if(curPage!=null)
			_curPage = curPage;
		
		hm.put("MEMBER_SEQ", str);
		hm.put("FROM_NUMBER", (Integer.parseInt(_curPage)-1)*Integer.parseInt(_pageSize));
		hm.put("TO_NUMBER", Integer.parseInt(_curPage)*Integer.parseInt(_pageSize));
		
		try {
			lt = (ArrayList)sqlMapper.queryForList("member.getUserArticle", hm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return lt;
	}
	
	public HashMap getUserInfo(String num, String g_num) {
		HashMap hm = new HashMap();
		HashMap return_hm = new HashMap();
		
		
		hm.put("MEMBER_SEQ", num);
		hm.put("MEMBER_GROUPSEQ", g_num);
		
		try {
			return_hm = (HashMap) sqlMapper.queryForObject("member.getUserInfo", hm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return return_hm;
	}
	
	public HashMap getMyInfo(){
		HashMap hm = new  HashMap();
		
		return hm;
	}
}
